<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/8 13:35
*/
declare(strict_types=1);
namespace app\store\service\agent;

use app\store\model\agent\MoneyLog;
use app\common\service\agent\Common as AgentCommonService;
use app\common\service\BaseService;
use app\store\model\agent\Promoter;
use app\store\model\agent\Rel;
use app\store\model\agent\Channel as ChannelModel;


class Achievement extends BaseService
{

    /**获取业绩
     * @param $agent_user_id
     */
    public function getInfo($agent_user_id): array
    {
        $channel_user = ChannelModel::where(['user_id' => $agent_user_id,'is_del' => 0])->find();
        $promoter_user = Promoter::where(['user_id' => $agent_user_id,'is_del' => 0])->find();
        if(!$channel_user && !$promoter_user){
            throwError('不是代理用户');
        }

        if($channel_user){
            $low_promoters = Promoter::where(['channel_id' => $channel_user->id,'is_del' => 0])->column('user_id');
            $low_promoter_num = count($low_promoters);
            $agent_user_ids = array_merge($low_promoters,[$agent_user_id]);
        }else{
            $low_promoter_num = 0;
            $agent_user_ids = [$agent_user_id];
        }


        //收益相关
        $agentCommonService = new AgentCommonService();
        $today_profit = $agentCommonService->getProfit('today',$agent_user_id);
        $yesterday_profit = $agentCommonService->getProfit('yesterday',$agent_user_id);
        $thirtyday_profit = $agentCommonService->getProfit('thirtyday',$agent_user_id);
        $yesterday_active_num = $agentCommonService->getYesterdayActiveNum($agent_user_id);

        $condition = [
            ['promoter_user_id','IN',$agent_user_ids],
            ['is_del','=',0]
        ];
        $player_list = Rel::with(['user.avatar'])->where($condition)
            ->select()
            ->each(function (&$item){
                $item['mobile'] = $item['user']['mobile'] ?? '';
                $item['nick_name'] = $item['user']['nick_name'] ?? '';
                $item['avatar_url'] = $item['user']['avatar_url'] ?? '';
                $item['pay_money'] = $item['user']['pay_money'] ?? '';
                unset($item['user']);
            })
            ->toArray();
        $total_player_user_num = count($player_list);
        //下级推广员
        $low_promoter_list = [];
        if($channel_user){
            $low_promoter_list = Promoter::with(['user.avatar'])
                ->field('user_id,divide,channel_id')
                ->where(['channel_id' => $channel_user->id,'is_del' => 0])
                ->select()
                ->each(function (&$item){
                    $item['mobile'] = $item['user']['mobile'] ?? '';
                    $item['nick_name'] = $item['user']['nick_name'] ?? '';
                    $item['avatar_id'] = $item['user']['avatar_id'] ?? 0;
                    $item['avatar_url'] = $item['user']['avatar_url'] ?? '';
                    unset($item['user']);
                    $item['thirty_day_profit'] = (new AgentCommonService)->getProfit('thirtyday',$item['user_id']);  //过去30天业绩
                })
                ->toArray();
        }

        return [
            'overview' => [
                'low_promoter_num' => $low_promoter_num,
                'total_player_num' => $total_player_user_num,
                'today_profit' => sprintf('%0.2f',$today_profit),
                'yesterday_profit' => sprintf('%0.2f',$yesterday_profit),
                'thirtyday_profit' => sprintf('%0.2f',$thirtyday_profit),
                'yesterday_active_num' => $yesterday_active_num,
            ],
            'low_promoter_list' => $low_promoter_list,
            'player_info' => [
                'total_pay_money' => array_sum(array_column($player_list,'pay_money')),
                'player_list' => $player_list
            ],
        ];
    }

    /**获取代理额外信息
     * @param $agent_user_id
     */
    public function getExtraInfo($agent_user_id): array
    {
        $player_num = Rel::where(['promoter_user_id' => $agent_user_id,'is_del' => 0])->count();
        $channel_user = ChannelModel::where(['user_id' => $agent_user_id,'is_del' => 0])->find();
        $low_promoter_num = 0;
        if($channel_user){
            $low_promoter_num = Promoter::where(['channel_id' => $channel_user->id,'is_del' => 0])->count();
        }
        return [
            'total_player_num' => $player_num,
            'low_promoter_num' => $low_promoter_num
        ];
    }


    /**业绩列表
     * @param $params
     * @return array
     */
    public function getIndex($params):array
    {
        $filter = [];
        if(!empty($params['start_time']) && !empty($params['end_time'])){
            $filter[] = ['created_at', '>=', $params['start_time'].' 00:00:00'];
            $filter[] = ['created_at', '<', date('Y-m-d H:i:s',strtotime($params['end_time']) + 86400)];
        }
        if(!empty($params['agent_user_id'])){
            $filter[] = ['agent_user_id','=',$params['agent_user_id']];
        }
        $channel_user_ids = ChannelModel::where(['is_del' => 0])->column('user_id');
        $filter[] = ['agent_user_id','IN',$channel_user_ids];
        return MoneyLog::with(['user'])->where($filter)
            ->order('id','DESC')
            ->paginate($params['limit'] ?? 15)
            ->each(function (&$item){
                $extra_info = $this->getExtraInfo($item['agent_user_id']);
                $item['total_player_num'] = $extra_info['total_player_num'];
                $item['low_promoter_num'] = $extra_info['low_promoter_num'];
            })
            ->toArray();
    }

}